package com.appinfo.controller;

import com.appinfo.annotation.AvoidRepeatableCommit;
import com.appinfo.pojo.AppCategory;
import com.appinfo.pojo.AppInfo;
import com.appinfo.pojo.DataDictionary;
import com.appinfo.pojo.DevUser;
import com.appinfo.service.AppCategoryService;
import com.appinfo.service.AppService;
import com.appinfo.service.DataDictionaryService;
import com.appinfo.utils.CheckObjectIsNull;
import com.appinfo.vo.AppInfoVo;
import com.appinfo.vo.AppVersionVo;
import com.appinfo.vo.Pages;
import com.appinfo.vo.QueryVo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/dev/flatform/app")
public class DevAppController {
    private static final String APP_STATUS = "APP_STATUS"; //状态
    private static final String APP_FLATFORM = "APP_FLATFORM"; //平台

    private static final List<String> allowType = Arrays.asList(".png",".jpeg"
            ,".jpg");

    @Autowired
    private AppService appService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private AppCategoryService appCategoryService;


    /**
     * 分页展示app信息列表
     * @param request
     * @param devUser
     * @param pages
     * @param model
     * @param queryVo
     * @return
     */
    @RequestMapping("/list")
    public String toAppList(HttpServletRequest request, DevUser devUser, Pages pages ,
                            Model model,QueryVo queryVo){
        request.setAttribute("user",devUser);
        pages = appService.queryAppInfoPage(pages,queryVo);
        model.addAttribute("pages",pages); //分页数据
        List<AppInfoVo> appInfoVos = pages.getRows();
        //状态栏
        List<DataDictionary> appDic = dataDictionaryService.queryAppDataDicList(APP_STATUS);
        List<DataDictionary> flatFormDic = dataDictionaryService.queryAppDataDicList(APP_FLATFORM);
        //一、二、三级分类列表
        List<AppCategory> categoryLevel1List = appCategoryService.queryCategoryLevel(null);

        List<Long> CL1Pids = categoryLevel1List.stream().map(appCategory -> {
            Long cl1Pid = appCategory.getId();
            return cl1Pid;
        }).collect(Collectors.toList());


        List<AppCategory> categoryLevel2List = appCategoryService.queryCategoryLevel(CL1Pids);

        List<Long> CL2Pids = categoryLevel2List.stream().map(appCategory -> {
            Long cl2Pid = appCategory.getId();
            return cl2Pid;
        }).collect(Collectors.toList());

        List<AppCategory> categoryLevel3List = appCategoryService.queryCategoryLevel(CL2Pids);

        //写入下拉列表
        model.addAttribute("querySoftwareName",pages.getQuerySoftwareName());
        model.addAttribute("queryStatus",pages.getQueryStatus());
        model.addAttribute("queryFlatformId",pages.getQueryFlatformId());
        model.addAttribute("queryCategoryLevel1",pages.getQueryCategoryLevel1());
        model.addAttribute("queryCategoryLevel2",pages.getQueryCategoryLevel2());
        model.addAttribute("queryCategoryLevel3",pages.getQueryCategoryLevel3());

        //属性
        model.addAttribute("categoryLevel1List",categoryLevel1List);
        model.addAttribute("categoryLevel2List",categoryLevel2List);
        model.addAttribute("categoryLevel3List",categoryLevel3List);
        model.addAttribute("statusList",appDic);
        model.addAttribute("flatFormList", flatFormDic);
        model.addAttribute("appInfoList",appInfoVos); //信息列表

        return "developer/appinfolist";
    }

    /**
     * 前往app信息添加页面
     * @param request
     * @param devUser
     * @return
     */
    @RequestMapping("/appinfoadd")
    public String toAppInfoAdd(HttpServletRequest request,DevUser devUser){
        request.setAttribute("user",devUser);
        return "developer/appinfoadd";
    }

    /**
     * 添加app基础信息
     * @param devUser
     * @param appInfo
     * @param request
     * @return
     */
    @RequestMapping("/appinfoaddsave")
    public String saveApp(DevUser devUser, AppInfo appInfo, HttpServletRequest request
            , MultipartFile file,Model model) {
        if(file == null){
            model.addAttribute("fileUploadError","上传失败！");
            return "forward:/dev/flatform/app/appinfoadd";
        }
        Resource resource = file.getResource();
        request.setAttribute("user",devUser);
        String oFileName = file.getOriginalFilename();
        String suffixName = oFileName.substring(oFileName.lastIndexOf('.'));
        String fileName = appInfo.getAPKName()+oFileName.substring(oFileName.lastIndexOf('.'));
        long size = file.getSize();

        if(allowType.get(0).equals(suffixName) || allowType.get(1).equals(suffixName) ||
                allowType.get(2).equals(suffixName) && size < 50*1024){
            //路径
            try {
                String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
                File localFile = new File(path, fileName);
                appInfo.setLogoPicPath("/upload/" + fileName);
                appInfo.setLogoLocPath(path + fileName);
                file.transferTo(localFile);
                appService.saveApp(appInfo, devUser);
                return "redirect:/dev/flatform/app/list";
            }catch (IOException e){
                e.printStackTrace();
                model.addAttribute("fileUploadError","上传失败！");
                return "forward:/dev/flatform/app/appinfoadd";
            }

        } else {
            request.setAttribute("fileUploadError","上传文件格式或大小不正确！");
            return "forward:/dev/flatform/app/appinfoadd";
        }

    }


    /**
     * 前往修改app基础信息页面
     * @param devUser
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/appinfomodify")
    public String toUpdateAppInfo(DevUser devUser, @RequestParam("id")Long id, Model model){
        model.addAttribute("user",devUser);
        AppInfoVo appInfoVo = appService.queryAppInfoById(id);
        model.addAttribute("appInfo",appInfoVo);
        return "developer/appinfomodify";
    }

    /**
     * 修改app基础信息
     * @param devUser
     * @param appInfoVo
     * @param model
     * @return
     */
    @RequestMapping("/appinfomodifysave")
    public String updateAppInfo(DevUser devUser, AppInfoVo appInfoVo, Model model
            , HttpServletRequest request, MultipartFile file){
        model.addAttribute("user", devUser);
        if(file == null){
            model.addAttribute("fileUploadError","上传失败！");
            return "forward:/dev/flatform/app/appinfomodify";
        }

        if(file.isEmpty()){
            appService.updateAppInfoByVo(appInfoVo,devUser);
            return "redirect:/dev/flatform/app/list";
        }else {

            String oFileName = file.getOriginalFilename();
            String suffixName = oFileName.substring(oFileName.lastIndexOf('.'));
            String fileName = appInfoVo.getAPKName() + oFileName.substring(oFileName.lastIndexOf('.'));
            long size = file.getSize();

            if (allowType.get(0).equals(suffixName) || allowType.get(1).equals(suffixName) ||
                    allowType.get(2).equals(suffixName) && size < 50 * 1024) {
                //路径
                try {
                    String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
                    File localFile = new File(path, fileName);
                    appInfoVo.setLogoPicPath("/upload/" + fileName);
                    appInfoVo.setLogoLocPath(path + fileName);
                    file.transferTo(localFile);
                    appService.updateAppInfoByVo(appInfoVo, devUser);
                    return "redirect:/dev/flatform/app/list";

                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("fileUploadError", "上传失败！");
                    return "forward:/dev/flatform/app/appinfomodify";
                }


            } else {
                request.setAttribute("fileUploadError", "上传文件格式或大小不正确！");
                return "forward:/dev/flatform/app/appinfomodify";
            }
        }


    }

    /**
     * 查看APP信息
     */
    @RequestMapping(value = "/checkAppInfo")
    public String checkAppInfo(@RequestParam(value = "appInfoId",required = false) Long appInfoId,
                               Model model) {

        AppInfoVo appInfoVo = appService.checkAppInfoById(appInfoId);
        List<AppVersionVo> appVersionList = appService.checkVersionInfoById(appInfoId);
        model.addAttribute("appInfo",appInfoVo);
        model.addAttribute("appVersionList",appVersionList);
        return "developer/appinfoview";

    }


    /**
     * 删除APP
     */
    @RequestMapping(value = "/delAppInfo")
    public String delAppInfo(@RequestParam(value = "appInfoId",required = false) Long appInfoId) {

        appService.delAppInfoById(appInfoId);
        return "redirect:/dev/flatform/app/list";
    }


    /**
     *APP上下架
     */
    @RequestMapping("/sale.json")
    public Map<String,Object> updateSaleStatusByAppId(@RequestParam(value = "appid",required = false) Long appid) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("errorCode", "0");

        if (appService.updateSaleStatusByAppId(appid)) {
            resultMap.put("resultMsg", "success");
        } else {
            resultMap.put("resultMsg", "failed");
            resultMap.put("errorCode", "exception000001");
            resultMap.put("errorCode", "param000001");
        }

        return resultMap;

    }

    @RequestMapping("/delfile.json")
    @ResponseBody
    public String delFile(@RequestParam("id")Long id,@RequestParam("flag")String flag){
        Boolean ret = appService.DelFile(id,flag);
        if(ret) {
            return "{\"result\":\"success\"}";
        }else {
            return "{\"result\":\"failed\"}";
        }
    }


}
